#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <sys/socket.h>
#include <fcntl.h>
#include "http.h"
//./Http_client http://1153288396.rsc.cdn77.org/img/cdn77-test-563kb.jpg
int main(int argc,char *argv[])
{
    if(argc < 0){
        fprintf(stderr,"usage: http_client URL\n");
        return  -1;
    }
    // 1. 解析URL到任务体内创建结构体
    taskInfo  *task = createTask();
    if(task == NULL){
        return  -1;
    }
    // 根据URL  解析 主机名 资源路径  文件名 存到  这个结构体里面
    if(parser_task(argv[1],task) < 0){
        releaseTask(task);
        return -1;
    }
    int sock= init_socket(task);
    if(sock < 0){
        releaseTask(task);
        return -1;
    }
    //构造HTTP请求头，循环发送
    HeaderBuffer  *request_header = build_request_header(task);
    if(request_header == NULL){
        releaseHeaderBuffer(request_header);
        return  -2;
    }
    //构造请求头成功打印消息
    //发送消息
    printf("ready to send!\n");
    ssize_t  bytes = send_data_bytes(sock,request_header->header, request_header->pos);
    if(bytes < 0){
        fprintf(stderr ,"send data %ld bytes error!",bytes);
        releaseHeaderBuffer(request_header);
        close(sock);
        return  -2;
    }
    releaseHeaderBuffer(request_header);
    // 4. 收取HTTP响应头，把响应头收完，有可能出错或收到完整的数据
    HeaderBuffer *response_header = rcv_response_header(sock);
    if(response_header == NULL){
        releaseHeaderBuffer(response_header);
        return -3;
    }
    // 解析响应
    if(get_status(response_header) < 0){
        releaseHeaderBuffer(response_header);
        return -3;
    }
    unsigned long cnt_size = 0;
    // 判断是否要分离响应头和数据域
    get_content_size(request_header,"Content-Length: ",&cnt_size);
    printf("response content-length: %ld\n", cnt_size);
    //分离数据并且存储到文件中
    int fd = open(task->filename,O_CREAT|O_WRONLY|O_TRUNC,0666);
    if(fd < 0){
        perror("open : ");
        releaseHeaderBuffer(response_header);
        return  -3;
    }
    size_t t= init_file(response_header,fd);
    cnt_size -=t;
    size_t cnt;
    cnt = receive_bytes(sock,fd,cnt_size);
    if (cnt ==cnt_size){
        printf("download success!\n");
    } else{
        printf("download failed!\n");
    }
    close(fd);
    releaseHeaderBuffer(response_header);
    close(sock);
    releaseTask(task);
    return 0;
}
